<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProjectCheckIn;
use Illuminate\Http\Request;

class ProjectCheckinController extends Controller
{

    public function defaultValue(Request $request, $project_id) {
        $node = Project::findOrFail($project_id);


        return $this->returnJSON([
            'address' => $node->address
        ], 0, '');
    }
    public function index(Request $request, $project_id) {
        Project::findOrFail($project_id);


        $perPage = $request->get('perPage', 10);
        $query = ProjectCheckIn::query()->where('project_id', '=', $project_id)->orderBy('begin', 'desc');

        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function store(Request $request, $project_id) {
        Project::findOrFail($project_id);

        $this->validate($request, [
            'begin' => 'required',
            'end' => 'required',
            'reward_time' => 'required',
            'distance' => 'required',
            'address' => 'required'
        ]);

        $node = new ProjectCheckIn();
        $data = $request->only([
            'begin',
            'end',
            'reward_time',
            'distance',
            'address'
        ]);

        // default values;
        $data['project_id'] = $project_id;
        $data['code'] = rand(100000, 999999);



        $node->fill($data);

        if ($node->save()) {
            return $this->returnJSON(null, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function destroy(Request $request, $project_id, $id)
    {
        Project::findOrFail($project_id);

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (ProjectCheckIn::whereRaw('id IN (?)', [$ids])->delete()) {
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }
}
